package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskInfoLogsMapper;
import com.heima.schedule.mapper.TaskInfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-02 10:39
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskInfoMapper taskInfoMapper;

    @Autowired
    private TaskInfoLogsMapper taskInfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addTask(Task task) {

        //1.添加数据库
        Long taskId = addTaskToDb(task);

        //2.添加缓存
        addTaskToCache(task);
        return taskId;
    }

    @Override
    public void deleteTask(long taskId) {

        //1.删除数据库
        Task task = deleteTaskToDb(taskId);

        //2.删除缓存
        deleteTaskToCache(task);

    }

    @Override
    public Task pollTask(int taskType, int taskPriority) {
        //从list拉取任务

        String key = taskType + "_" + taskPriority; //topic_1_50
        String taskId = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if(StringUtils.isBlank(taskId)){
            return null;
        }

        //修改数据库状态
        updateDbStatus(Long.valueOf(taskId),ScheduleConstants.EXECUTED);

        String task = (String) cacheService.hGet(ScheduleConstants.HASH_NAME, taskId);
        cacheService.hDelete(ScheduleConstants.HASH_NAME, taskId);



        return JSON.parseObject(task,Task.class);
    }

    private TaskinfoLogs updateDbStatus(Long taskId, int status) {
        taskInfoMapper.deleteById(taskId);

        TaskinfoLogs taskinfoLogs = taskInfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        int i = taskInfoLogsMapper.updateById(taskinfoLogs);
        if(i == 0){
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"数据已经被人修改，操作失败!");
        }

        return taskinfoLogs;

    }

    private void deleteTaskToCache(Task task) {

        //获取当前时间
        long time = System.currentTimeMillis();
        //获取5分钟之后的时间
        long after5minutes = DateTime.now().plusMinutes(5).toDate().getTime();
        //获取任务时间
        long executeTime = task.getExecuteTime();

        String key = task.getTaskType() + "_" + task.getPriority(); //topic_1_50

        String taskIdStr = task.getTaskId().toString();
        if(executeTime <= time){
            //1.删除list
            cacheService.lRemove(ScheduleConstants.TOPIC + key,0, taskIdStr);
            //3.删除hash中的数据
            cacheService.hDelete(ScheduleConstants.HASH_NAME,taskIdStr,JSON.toJSONString(task));
        }else if(executeTime <= after5minutes){
            //2.删除zset
            cacheService.zRemove(ScheduleConstants.FUTURE + key,taskIdStr);
            //3.删除hash中的数据
            cacheService.hDelete(ScheduleConstants.HASH_NAME,taskIdStr,JSON.toJSONString(task));
        }


    }

    private Task deleteTaskToDb(long taskId) {

        TaskinfoLogs taskinfoLogs = updateDbStatus(taskId, ScheduleConstants.CANCELLED);

        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs,task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        return task;
    }

    private void addTaskToCache(Task task) {
        //获取当前时间
        long time = System.currentTimeMillis();
        //获取5分钟之后的时间
        long after5minutes = DateTime.now().plusMinutes(5).toDate().getTime();
        //获取任务时间
        long executeTime = task.getExecuteTime();

        String key = task.getTaskType() + "_" + task.getPriority(); //topic_1_50

        String taskIdStr = task.getTaskId().toString();
        boolean flag = false;
        if(executeTime <= time){
            //立即要执行，放list
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, taskIdStr);
            flag = true;
        }else if(executeTime <= after5minutes){
            //小于等于5分钟，放入zet
            cacheService.zAdd(ScheduleConstants.FUTURE + key,taskIdStr
            ,task.getExecuteTime());
            flag = true;
        }

        if(flag){
            cacheService.hPut(ScheduleConstants.HASH_NAME,taskIdStr,JSON.toJSONString(task));
            //更新数据库状态
            taskInfoMapper.update(null, Wrappers.<Taskinfo>lambdaUpdate()
                    .eq(Taskinfo::getTaskId,task.getTaskId())
                    .set(Taskinfo::getInRedis,1)
            );
        }

    }


    private Long addTaskToDb(Task task) {
        //操作两张表

        //1.任务表
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task,taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        taskInfoMapper.insert(taskinfo);

        //设置任务id方便后边写缓存使用
        task.setTaskId(taskinfo.getTaskId());

        //2.日志表
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo,taskinfoLogs);
        taskinfoLogs.setVersion(1);
        taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);

        taskInfoLogsMapper.insert(taskinfoLogs);

        return taskinfo.getTaskId();
    }

    //每分钟执行一次，将zset数据同步到list中
    @Override
    @Scheduled(cron = "0 * * * * ?")
    public void zsetToList(){
        //通过scan命令找到所有的zset
        String token = cacheService.tryLock("zsetToList", 10 * 1000);
        if(token != null){
            System.out.println("zsetToList业务执行完毕");
            Set<String> scan = cacheService.scan(ScheduleConstants.FUTURE + "*");
            if(CollectionUtils.isEmpty(scan)){
                return;
            }

            //获取到zset key
            for (String zsetKey : scan) {
                //zsetKey 转换成 list key    future_1_50 -> topic_1_50
                String listKey = zsetKey.replace(ScheduleConstants.FUTURE, ScheduleConstants.TOPIC);
                //通过zset找到所有到期数据
                Set<String> taskIds = cacheService.zRangeByScore(zsetKey, 0, System.currentTimeMillis());
                //管道接口调用
                cacheService.refreshWithPipeline(zsetKey,listKey,taskIds);
            }

        }

    }



    //每分钟执行一次，将zset数据同步到list中
    @Scheduled(cron = "0 0/5 * * * ?")
    @PostConstruct
    public void dbToRedis(){
        //通过scan命令找到所有的zset
        String token = cacheService.tryLock("dbToRedis", 30 * 1000);
        if(token != null){
            System.out.println("dbToRedis业务执行");

            //1.查的数据必须在5分钟之内执行 2.数据在redis不存在
            Date date = DateTime.now().plusMinutes(5).toDate();

            List<Taskinfo> taskinfos = taskInfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                    .le(Taskinfo::getExecuteTime, date)
                    .eq(Taskinfo::getInRedis, 0)
            );
            if(CollectionUtils.isEmpty(taskinfos)){
                return;
            }

            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                //更新缓存
                addTaskToCache(task);
            }
        }

    }
}
